<script setup lang="ts">
import { pageUrl } from '@/utils/constants'
import { getMemberProfileApi } from '@/api/member'
import { payOrderApi } from '@/api/pay'
import _ from 'lodash'
import { computed, reactive, ref } from 'vue'
import { onShowRefreshData } from '@/utils/common'

// 获取页面参数
const props = defineProps<{
  orderId: string
  payPrice: string
}>()

const state = reactive({
  orderId: Number(props.orderId),
  balance: '0.00',
})

const getBalance = async () => {
  const res = await getMemberProfileApi()
  state.balance = res.result.money || '0.00'
}

// 表单数据
const formData = reactive({
  email: '',
  cardNumber: '',
  expiration: '',
  cvc: '',
  country: 'Hong Kong SAR, China'
})

// 支付方式列表
const payMethods = ref([
  { name: 'Visa', icon: '/static/icons/card1.svg', selected: true },
  { name: 'MasterCard', icon: '/static/icons/card2.svg', selected: false },
  { name: 'American Express', icon: '/static/icons/card3.svg', selected: false },
  { name: 'Discover', icon: '/static/icons/card4.svg', selected: false },
  { name: 'Diners Club', icon: '/static/icons/card5.svg', selected: false },
  { name: 'Maestro', icon: '/static/icons/card6.svg', selected: false },
  { name: 'JCB', icon: '/static/icons/card7.svg', selected: false }
])

// 格式化信用卡号
const formatCardNumber = (value: string) => {
  if (!value) return ''
  const v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '')
  const matches = v.match(/\d{4,16}/g)
  const match = matches && matches[0] || ''
  const parts = []
  for (let i = 0, len = match.length; i < len; i += 4) {
    parts.push(match.substring(i, i + 4))
  }
  if (parts.length) {
    return parts.join(' ')
  } else {
    return value
  }
}

// 处理卡号输入
const handleCardNumberInput = (e: any) => {
  formData.cardNumber = formatCardNumber(e.detail.value)
}

// 格式化有效期
const formatExpiration = (value: string) => {
  if (!value) return ''
  const v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '')
  if (v.length > 2) {
    return v.slice(0, 2) + '/' + v.slice(2, 4)
  }
  return v
}

// 处理有效期输入
const handleExpirationInput = (e: any) => {
  formData.expiration = formatExpiration(e.detail.value)
}

// 处理CVC输入
const handleCvcInput = (e: any) => {
  formData.cvc = e.detail.value.replace(/[^0-9]/gi, '').substring(0, 3)
}

const onPayment = async () => {
  if (!formData.email) {
    return uni.showToast({ title: 'Please enter your email', icon: 'none' })
  }
  if (!formData.cardNumber || formData.cardNumber.replace(/\s/g, '').length < 16) {
    return uni.showToast({ title: 'Please enter a valid card number', icon: 'none' })
  }
  if (!formData.expiration || formData.expiration.length < 5) {
    return uni.showToast({ title: 'Please enter expiration date', icon: 'none' })
  }
  if (!formData.cvc || formData.cvc.length < 3) {
    return uni.showToast({ title: 'Please enter security code', icon: 'none' })
  }
  
  uni.showLoading({ title: 'Processing payment...' })
  
  try {
    // 模拟支付处理
    setTimeout(() => {
      uni.hideLoading()
      uni.redirectTo({
        url: `${pageUrl['order-payment']}?id=${props.orderId}&pay_way=card`,
      })
    }, 1500)
  } catch (err: any) {
    uni.hideLoading()
    uni.showModal({
      title: 'Notice',
      content: err.data?.msg || 'Payment failed',
      showCancel: false,
    })
  }
}

onShowRefreshData(() => {
  getBalance()
})
</script>

<template>
  <view class="payment-container">
    <view class="money">
      <span class="currency">$</span>
      <span class="integer">{{ props.payPrice.split('.')[0] }}.</span>
      <span class="decimal">{{ props.payPrice.split('.')[1] }}</span>
    </view>
    <!-- 头部信息 -->
    <view class="header">
      <view class="credit-cards">
        <text>We accepts all major credit and debit cards.</text>
        <view class="card-logos">
          <image v-for="method in payMethods" :key="method.name" :src="method.icon" mode="aspectFit" class="card-logo" />
        </view>
      </view>
      
      <view class="payment-title">
        <text>Payment</text>
      </view>
      
      <view class="payment-description">
        <text>Enable more payment method types <text class="dashboard-link">in your dashboard</text>.</text>
      </view>
    </view>
    
    <!-- 支付表单 -->
    <view class="payment-form">
      <!-- 邮箱 -->
      <view class="form-group">
        <text class="label">Email</text>
        <input type="text" class="input" placeholder="you@example.com" v-model="formData.email" />
      </view>
      
      <!-- 卡号 -->
      <view class="form-group">
        <text class="label">Card Number</text>
        <input type="text" class="input card-input" placeholder="1234 1234 1234 1234" 
          :value="formData.cardNumber" 
          @input="handleCardNumberInput"
          maxlength="19" />
      </view>
      
      <!-- 有效期和安全码 -->
      <view class="form-row">
        <view class="form-group half">
          <text class="label">Expiration Date</text>
          <input type="text" class="input" placeholder="MM/YY" 
            :value="formData.expiration" 
            @input="handleExpirationInput"
            maxlength="5" />
        </view>
        
        <view class="form-group half">
          <text class="label">Security Code</text>
          <input type="text" class="input" placeholder="CVC" 
            :value="formData.cvc" 
            @input="handleCvcInput"
            password
            maxlength="3" />
        </view>
      </view>
      
      <!-- 国家/地区 -->
      <view class="form-group">
        <text class="label">Country/Region</text>
        <view class="select-wrapper">
          <picker mode="selector" :range="['Hong Kong SAR, China']" @change="(e) => formData.country = e.detail.value">
            <view class="input">{{ formData.country }}</view>
          </picker>
          <text class="select-arrow">▼</text>
        </view>
      </view>
      
      <!-- 支付按钮 -->
      <button class="pay-button" @tap="onPayment">Pay now</button>
    </view>
  </view>
</template>

<style lang="scss">
page {
  background-color: #ffffff;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
}

.payment-container {
  padding: 20rpx;
  box-sizing: border-box;

  .money {
    font-size: 48rpx;
    color: red;
    margin-right: 10rpx;
    text-align: center;
    margin: 20rpx 0 40rpx 0;
    font-weight: 600;
  }
}

.header {
  margin-bottom: 40rpx;
  
  .credit-cards {
    margin-bottom: 40rpx;
    
    text {
      display: block;
      font-size: 28rpx;
      color: #333;
      margin-bottom: 20rpx;
    }
    
    .card-logos {
      display: flex;
      flex-wrap: wrap;
      
      .card-logo {
        width: 80rpx;
        height: 50rpx;
        margin-right: 16rpx;
        margin-bottom: 16rpx;
      }
    }
  }
  
  .payment-title {
    font-size: 48rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .payment-description {
    font-size: 28rpx;
    color: #333;
    
    .dashboard-link {
      color: #0066cc;
      text-decoration: underline;
    }
  }
}

.payment-form {
  .form-group {
    margin-bottom: 30rpx;
    
    .label {
      display: block;
      font-size: 28rpx;
      color: #333;
      margin-bottom: 10rpx;
    }
    
    .input {
      width: 100%;
      height: 90rpx;
      border: 1px solid #ddd;
      border-radius: 8rpx;
      padding: 0 20rpx;
      font-size: 28rpx;
      box-sizing: border-box;
    }
    
    .select-wrapper {
      position: relative;
      
      .select-arrow {
        position: absolute;
        right: 20rpx;
        top: 30rpx;
        color: #999;
        font-size: 24rpx;
      }
    }
  }
  
  .form-row {
    display: flex;
    justify-content: space-between;
    
    .half {
      width: 48%;
    }
  }
  
  .pay-button {
    width: 100%;
    height: 90rpx;
    background-color: #000;
    color: #fff;
    border: none;
    border-radius: 8rpx;
    font-size: 32rpx;
    line-height: 90rpx;
    margin-top: 20rpx;
  }
}
</style>
